package logic

import (
	"context"
	"errors"
	"novel-start/models/mysql"

	"novel-start/novelrpc/internal/svc"
	"novel-start/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookShelfAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookShelfAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookShelfAddLogic {
	return &BookShelfAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookShelfAddLogic) BookShelfAdd(in *novelrpc.BookShelfAddRequest) (*novelrpc.BookShelfAddResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if err := user.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}

	var novel mysql.Novel

	if err := novel.FindNovelById(mysql.DB, in.NovelId); err != nil {
		return nil, errors.New("该书本已下架")
	}

	bookShelf := &mysql.BookShelf{
		UserId:  in.UserId,
		NovelId: in.NovelId,
	}

	if err := bookShelf.BookShelfAdd(mysql.DB); err != nil {
		return nil, err
	}

	return &novelrpc.BookShelfAddResponse{
		BookShelfId: int64(bookShelf.ID),
	}, nil
}
